package com.blockmeta.bbs.businesslibrary.receiver;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.core.content.FileProvider;

import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.NetworkStateUtil;
import com.blockmeta.bbs.baselibrary.utils.permission.RequestPermissionUtil;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.service.DownloadService;

import java.io.File;

/**
 * Created by ShenLang on 2017/2/27.
 * APK更新
 */

public class ApkInstallReceiver extends BroadcastReceiver {
    private static int count;
    private static Context mContext;

    private static final int DOWN_LOAD_TRY_TIMES = 3;

    private static final long DELAY_TIME = 5 * 1000l;

    private static final int WHAT_DOWN_LOAD = 101;

    private static DownloadService.DownloadCallback mDownloadCallback;

    private static Handler m_DownloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mContext == null) return;
            switch (msg.what) {
                case WHAT_DOWN_LOAD:
                    if (!NetworkStateUtil.isNetWorkAvailable(mContext)) {
                        m_DownloadHandler.sendEmptyMessageDelayed(WHAT_DOWN_LOAD, DELAY_TIME);
                        return;
                    }
                    if (count >= DOWN_LOAD_TRY_TIMES) {
//							FDTToastUtils.showToast(MainActivity.this,"下载失败",false);
                        return;
                    }

                    downloadApkFile(mContext,mDownloadCallback);
                    count++;
                    break;
            }

        }
    };

    public static void downloadApkFile(final Context context,final DownloadService.DownloadCallback downloadCallback) {
        RequestPermissionUtil.requestStorage(new RequestPermissionUtil.OnPermissionGrantedListener() {
                                            @Override
                                            public void onPermissionGranted() {
                                                if(downloadCallback != null) {
                                                    mDownloadCallback = downloadCallback;
                                                }

                                                    DownloadService.bindService(context.getApplicationContext(), new ServiceConnection() {
                                                        @Override
                                                        public void onServiceConnected(ComponentName name, IBinder service) {
                                                            ((DownloadService.DownloadBinder) service).start(downloadCallback);
                                                        }

                                                        @Override
                                                        public void onServiceDisconnected(ComponentName name) {

                                                        }
                                                    });

                                            }

                                        }
        );


    }



    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        if (intent.getAction().equals(Constant.DOWN_LOAD_ACTION)) {
            boolean isloadSuccess = intent.getBooleanExtra(Constant.APK_FILE_IS_LOAD_SUCCESS, true);
            final String fileUrl = intent.getStringExtra(Constant.APK_FILE_PATH);

            if (!isloadSuccess)//下载失败,手动下载
            {//再次尝试
                m_DownloadHandler.sendEmptyMessageDelayed(WHAT_DOWN_LOAD, (count + 1) * DELAY_TIME);
            } else if (isloadSuccess)//手动下载完成
            {//直接安装
                installFile(context, fileUrl);
                mDownloadCallback = null;
            }
        }
    }

    private void installFile(Context context, String pFileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BaseApp.getApplicationId() + ".fileprovider", new File(pFileName));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(pFileName)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

}
